package org.huiway.huipicturebackend.api.imagesearch.sub;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.huiway.huipicturebackend.exception.BusinessException;
import org.huiway.huipicturebackend.exception.ErrorCode;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取以图搜图页面地址（step 1）
 */
@Slf4j
public class GetImagePageUrlApi {
    /**
     * 获取以图搜图页面地址
     *
     * @param imageUrl
     * @return
     */
    public static String getImagePageUrl(String imageUrl) {
        //1.准备请求参数
        Map<String, Object> formData = new HashMap<>();
        formData.put("image", imageUrl);
        formData.put("tn", "pc");
        formData.put("form", "pc");
        formData.put("image_source", "Pc_UPLOAD_URL");
        //获取当前时间戳
        long uptime = System.currentTimeMillis();
        //构造请求地址
        String url = "https://graph.baidu.com/upload?uptime=" + uptime;
        String acsToken = "jmM4zyI8OUixvSuWh0sCy4xWbsttVMZb9qcRTmn6SuNWg0vCO7N0s6Lffec+IY5yuqHujHmCctF9BVCGYGH0H5SH/H3VPFUl4O4CP1jp8GoAzuslb8kkQQ4a21Tebge8yhviopaiK66K6hNKGPlWt78xyyJxTteFdXYLvoO6raqhz2yNv50vk4/41peIwba4lc0hzoxdHxo3OBerHP2rfHwLWdpjcI9xeu2nJlGPgKB42rYYVW50+AJ3tQEBEROlg/UNLNxY+6200B/s6Ryz+n7xUptHFHi4d8Vp8q7mJ26yms+44i8tyiFluaZAr66/+wW/KMzOhqhXCNgckoGPX1SSYwueWZtllIchRdsvCZQ8tFJymKDjCf3yI/Lw1oig9OKZCAEtiLTeKE9/CY+Crp8DHa8Tpvlk2/i825E3LuTF8EQfzjcGpVnR00Lb4/8A";
        try {
            //2.发送请求
            HttpResponse httpResponse = HttpRequest.post(url)
                    //这里需要指定acs-token 不然会响应系统异常
                    .header("Acs-Token", acsToken)
                    .form(formData)
                    .timeout(5000)
                    .execute();
            //3.处理响应
            if (httpResponse.getStatus() != HttpStatus.HTTP_OK) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "接口调用失败");
            }
            //解析响应
            String body = httpResponse.body();
            Map<String, Object> result = JSONUtil.toBean(body, Map.class);
            //处理响应结果
            if (result == null || !Integer.valueOf(0).equals(result.get("status"))) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "接口调用失败");
            }
            Map<String, Object> data = (Map<String, Object>) result.get("data");
            //对 URL 进行解码
            String rawUrl = (String) data.get("url");
            String decodedUrl = URLUtil.decode(rawUrl, StandardCharsets.UTF_8);
            if (StrUtil.isBlank(decodedUrl)) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "未返回有效的结果地址");
            }
            // 解析参数
            Map<String, String> queryParams = parseQueryParams(decodedUrl);
            String sessionId = queryParams.get("session_id");
            String sign = queryParams.get("sign");

            // 拼接成真实图搜结果页面
            String finalUrl = StrUtil.format(
                    "https://graph.baidu.com/s?card_key=&entrance=GENERAL&extUiData%5BisLogoShow%5D=1&f=all&isLogoShow=1&session_id={}&sign={}&tpl_from=pc",
                    sessionId, sign
            );

            return finalUrl;


        } catch (Exception e) {
            log.error("调用百度以图搜图接口失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "搜索失败");
        }

    }

    /**
     * 解析 URL 查询参数为 Map
     */
    public static Map<String, String> parseQueryParams(String url) {
        Map<String, String> params = new HashMap<>();
        try {
            String query = url.contains("?") ? url.substring(url.indexOf('?') + 1) : "";
            for (String param : query.split("&")) {
                if (param.contains("=")) {
                    String[] kv = param.split("=", 2);
                    params.put(kv[0], kv[1]);
                }
            }
        } catch (Exception e) {
            log.error("解析 URL 参数失败", e);
        }
        return params;
    }

    public static void main(String[] args) {
        //测试以图搜图功能
        String imageUrl = "https://img0.baidu.com/it/u=2181884095,3910035095&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=1736";
        String searchResultUrl = getImagePageUrl(imageUrl);
        System.out.println("搜索成功，结果Url:" + searchResultUrl);
    }
}
